﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HostComputerPlatform.Services
{
    public class ModuleResultService : IModuleResultService
    {
        private readonly ConcurrentDictionary<string, Dictionary<string, object>> _moduleResults =
            new ConcurrentDictionary<string, Dictionary<string, object>>();

        public ModuleResultService()
        {
        }

        public void StoreResult(string moduleId, Dictionary<string, object> outputs)
        {
            if (string.IsNullOrEmpty(moduleId) || outputs == null) return;

            _moduleResults.AddOrUpdate(moduleId, outputs, (id, oldOutputs) => outputs);
        }

        public Dictionary<string, object> GetModuleOutputs(string moduleId)
        {
            return _moduleResults.TryGetValue(moduleId, out var outputs) ? outputs : null;
        }

        public T GetOutputValue<T>(string sourceModuleId, string outputPortName)
        {
            if (_moduleResults.TryGetValue(sourceModuleId, out var outputs))
            {
                if (outputs.TryGetValue(outputPortName, out var value) && value is T typedValue)
                {
                    return typedValue;
                }
            }
            return default;
        }

        public void ClearResults()
        {
            _moduleResults.Clear();
        }
    }
}
